/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.corticon.dialogs.web.designer;

import com.corticon.dialogs.model.User;
import com.corticon.dialogs.service.PortalUserService;
import com.corticon.dialogs.util.security.PasswordNotMatchException;
import com.corticon.dialogs.web.BaseController;
import com.corticon.dialogs.designer.licence.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.DisabledException;
import org.springframework.security.ui.savedrequest.SavedRequest;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Controller for user login
 *
 * @author Minghui Zheng
 */
@Controller
public class UserLoginController extends BaseController {

    private Log logger = LogFactory.getLog(UserLoginController.class);
    public static final String SPRING_SECURITY_SAVED_REQUEST_KEY =
            "SPRING_SECURITY_SAVED_REQUEST_KEY";
    public static final String LAST_USERNAME_KEY = "LAST_USERNAME_KEY";
    @Resource
    private PortalUserService portalUserService;
    @Resource
    private LicenceManager licenceManager;

    //private static final String MAIN_PAGE = "/index.jsp";
    private static final String DIALOG_PAGE = "/designer/questionnaire/list.html";
    private static final String LOGIN_PAGE = "/login.jsp";
    private static final String LICENSE_FILE_NAME = "DesignerLicense.lic";
    static String classPath = UserLoginController.class.getResource("/").getPath();

    // Invalid license message, wrongly license file or license doesn't exist.
    private static final String INVALID_LICENSE = "Invalid designer license.";
    // Too many users
    private static final String EXCEEDED_MAX_USERS
        = "The number of users have exceed the current license's limitation. Please purchase new one.";
    // Exired date
    private static final String EXPIRED_DATE = "Your license is expired."; 

    private String validLicense() {
        String message = "";
        // Load the license file
        licenceManager.load(classPath + LICENSE_FILE_NAME);

        // Verify the signature of license
        if (!licenceManager.verify()) {
            message = INVALID_LICENSE;
        // Check the expired date
        } else if (!licenceManager.checkExpiredDate()) {
            message = EXPIRED_DATE;
        // Check the count of user.
        } else if (!licenceManager.checkMAXUser()) {
            message = EXCEEDED_MAX_USERS;
        }
        return message;
    }
    
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(HttpServletRequest request) {
        String message = validLicense();
        if (!("".equals(message))) {
            request.getSession().setAttribute("licence_message", message);
            return this.redirectPrefix + LOGIN_PAGE;
        }

        logger.debug("-----------------------do user login--------------");

        User guest = new User();
        guest.setUsername(request.getParameter("username"));
        guest.setPassword(request.getParameter("password"));

        String[] messagesKeys = {"userdesabled", "errors_username", "errors_password"};
        User user = null;
        this.cleanMessages(messagesKeys, request);
        try {
            user = portalUserService.userLogin(guest, request);
        } catch (DisabledException de) {
            request.getSession().setAttribute("userdesabled", de.getMessage());
            logger.debug(
                    "------------------------------Login failed: This account has bean disabled.");
        } catch (UsernameNotFoundException ue) {
            request.getSession().setAttribute("errors_username", ue.getMessage());
        } catch (PasswordNotMatchException pe) {
            request.getSession().setAttribute("errors_password", pe.getMessage());
        }
        if (user != null) {//if pass authentication
            request.getSession().setAttribute(LAST_USERNAME_KEY, guest.getUsername());
            SavedRequest savedRequest = (SavedRequest) request.getSession().getAttribute(
                    SPRING_SECURITY_SAVED_REQUEST_KEY);
            if (savedRequest != null) {//return url before login
                String queryString =
                        savedRequest.getQueryString() == null ? "" : "?" + savedRequest.getQueryString();
//                return this.redirectPrefix + savedRequest.getContextPath() + queryString;//ignore "/dialogs"
                //return this.redirectPrefix + StringUtils.removeStart(savedRequest.getRequestURI(),
                //    savedRequest.getContextPath()) + queryString;
                String jumpUrl = StringUtils.removeStart(savedRequest.getRequestURI(), savedRequest.getContextPath()) + queryString;
                if (jumpUrl.equals("/")) {
                    return this.redirectPrefix + DIALOG_PAGE;
                } else {
                    return this.redirectPrefix + jumpUrl;
                }

            } else {
                //return this.redirectPrefix + MAIN_PAGE;
                return this.redirectPrefix + DIALOG_PAGE;
            }
        }

        request.getSession().setAttribute(LAST_USERNAME_KEY, guest.getUsername());//for display previously inputed username
        return this.redirectPrefix + LOGIN_PAGE;//if failed authentication
    }
}
